package com.example.pomelo_home.dao;

import com.example.pomelo_home.entity.Activity;
import com.example.pomelo_home.entity.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;

@Repository
public interface OrderRepository extends JpaRepository<Order,Integer> {
    //统计图：订单模块（管理）
    @Query(value = "SELECT DATE(o.application_time) AS orderDate, COUNT(o) AS count FROM activityorder o WHERE o.application_time BETWEEN :startDate AND :endDate GROUP BY DATE(o.paymentTime)", nativeQuery = true)
    List<Object[]> countOrdersByDate(@Param("startDate") Date startDate, @Param("endDate") Date endDate);
    //通过判断活动名或订单状态的值来进行查询（管理）
    @Query(value = "SELECT * FROM activityorder WHERE (:status IS NULL OR order_status = :status) AND (:title IS NULL OR activity_title LIKE %:title%)", nativeQuery = true)
    public Page<Order> findByLike(@Param("status") String orderStatus, @Param("title") String activityTitle, Pageable pageable);
    //审核订单:修改订单状态（管理）
    @Modifying
    @Transactional
    @Query(value = "UPDATE activityorder SET order_status='未支付' WHERE order_id=?", nativeQuery = true)
    public int audit(Integer orderId);
    //删除订单（管理）
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM activityorder WHERE order_id=?", nativeQuery = true)
    public int deleteOrder(Integer orderId);
    //订单报名：新增一个状态为待审核的订单（小程序）
    @Modifying
    @Transactional
    @Query(value = "INSERT INTO activityorder(activity_title,openid,name,phone,order_status,payment_amount,application_time) VALUES (?,?,?,?,'待审核',?,?)", nativeQuery = true)
    public int Application(String activityTitle, String openid, String name, Integer phone, Double paymentAmount,Date applicationTime);
    //查询所有订单（小程序）
    @Query(value = "SELECT * FROM activityorder WHERE order_status !='已删除'", nativeQuery = true)
    public List<Order> findAllOrder();
    //删除订单:客观原因仅仅修改订单状态（小程序）
    @Modifying
    @Transactional
    @Query(value = "UPDATE activityorder SET order_status='已删除' WHERE order_id=?", nativeQuery = true)
    public int delete(Integer orderId);
    //取消订单:（小程序）
    @Modifying
    @Transactional
    @Query(value = "UPDATE activityorder SET order_status='已取消' WHERE order_id=?", nativeQuery = true)
    public int cancel(Integer orderId);
    //支付订单:（小程序）
    @Modifying
    @Transactional
    @Query(value = "UPDATE activityorder SET order_status='已支付' WHERE order_id=?", nativeQuery = true)
    public int pay(Integer orderId);
}
